"""Administration functions

Handlers and utility functions for the background administration
functions of the choosegame system.
"""

import csv
import logging
import re
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext import db

import data
import util

class SecretHandler(webapp.RequestHandler):
  "Allow an admin to query or replace secret tokens"

  def GetTokenList(self):
    "Returns a list of dictionaries representing all the current auth tokens"

    secret_query = data.SecretEntry.all()
    res = secret_query.fetch(20)
    token_list = []
    if not res:
      pass
    else:
      for result in res:
        token_list.append({"facility": result.facility, "token": result.token})

    return token_list

  def get(self):
    "Entry point. Display with form only"

    template_values = {"token_list" : self.GetTokenList()}

    template_path = os.path.join(os.path.dirname(__file__),
                                 "templates/admin_tokens.html")
    self.response.out.write(template.render(template_path, template_values))


  def post(self):
    "Handle an update to the secrets list"

    facility = self.request.get("facility").strip()
    new_token = self.request.get("token").strip()

    template_values = {}

    if facility and new_token:
      logging.info("Updating auth token for %s" % facility)
      template_values["message"] = "Updated token for facility %s" % facility
      secret_query = data.SecretEntry.all()
      secret_query.filter("facility =", facility)
      res = secret_query.fetch(5)

      if not res:
        secret = data.SecretEntry()
        secret.facility = facility
      else:
        secret = res[0]
      secret.token = new_token
      secret.put()

      # check for extras and delete them.
    template_values["token_list"] = self.GetTokenList()

    template_path = os.path.join(os.path.dirname(__file__),
                                 "templates/admin_tokens.html")
    self.response.out.write(template.render(template_path, template_values))


application = webapp.WSGIApplication([('/admin/tokens', SecretHandler),
                                      ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
